package com.yunxun.service;
import com.yunxun.entity.ArticleEntity;
import com.yunxun.entity.MessageEntity;
import com.yunxun.mapper.ArticleMapper;
import com.yunxun.mapper.MessageMapper;
import com.yunxun.utils.DownWebPageUtil;
import com.yunxun.utils.LoadingArticleUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class MessageService {
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private ArticleMapper contentMapper;

    /**
     *
     * @param url
     * @param encoding
     * @param typeValue
     * @return 返回不为0即是插入成功
     * @throws Exception
     */
    @Transactional(rollbackFor={RuntimeException.class, Exception.class})
    public int insert(String url,String encoding,int typeValue){
        List<MessageEntity> messageEntities = null;
        messageEntities = new DownWebPageUtil().getMessageEntities(url,encoding,typeValue);
         List<ArticleEntity> contentEntities = new LoadingArticleUtil().getContent(messageEntities);
        int flag =0 ;
        if(messageEntities != null) {
            for (int i=0;i<messageEntities.size();i++) {
                flag = 0;
                messageEntities.get(i).setTypeValue(typeValue);
                flag = messageMapper.insertSelective(messageEntities.get(i));
                int mid =messageEntities.get(i).getMid();
                if (flag == 0){
                    try {
                        throw new Exception("插入资讯失败");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }finally {
                        return 0;
                    }
                }
                //将messageEntity主键设置进ContentEntity中的mid字段
                contentEntities.get(i).setMid(mid);
                flag = 0;
               flag = contentMapper.insertSelective(contentEntities.get(i));
                if (flag == 0){
                    try {
                        throw new Exception("插入资讯内容失败");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }finally {
                        return 0;
                    }
                }
            }
        }
        return flag;
    }

    /**
     *
     * @param messageEntity
     * @return
     */
    public List<MessageEntity> queryMessageByTypeValue(MessageEntity messageEntity){
        List<MessageEntity> messageEntities =new ArrayList<MessageEntity>();
        messageEntities = messageMapper.select(messageEntity);
        return messageEntities;
    }
}
